package IBBB.view;

import IBBB.model.UserMessage;
import IBBB.model.WordStockMessage;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import IBBB.network.sendmessage.send_query_word_stock;
import IBBB.network.sendmessage.send_login;
import IBBB.network.sendmessage.send_register;

class WaitBox extends HBox {
    private ImageView imageView = new ImageView();
    private Text text = new Text();

    public WaitBox(String t) {
        this.setPadding(new Insets(0,0,0,10));
        this.setSpacing(10);
        this.setAlignment(Pos.CENTER_LEFT);
        this.setPrefSize(260,45);
        imageView.setFitWidth(32);
        imageView.setFitHeight(32);
        imageView.setImage(new Image("wait.png"));

        text.setFont(new Font(24));
        text.setText(t);
        getChildren().addAll(imageView, text);
    }
}


public class Login {
    @FXML
    private StackPane container;
    @FXML
    private ComboBox<String> idText;
    @FXML
    private PasswordField passwordText;
    @FXML
    private Button loginButton;
    @FXML
    private Button signupButton;


    public UserMessage getUserMessage() {
        return userMessage;
    }

    private UserMessage userMessage;

    public WordStockMessage getWordStockMessage() {
        return wordStockMessage;
    }

    private WordStockMessage wordStockMessage;
    private Stage primary;
    private Stage stage;

    public StringProperty onSuccessProperty() {
        return onSuccess;
    }

    private StringProperty onSuccess = new SimpleStringProperty("init");


    @FXML
    private void initialize() {
        File id = new File("src/IBBB/temp/userName.tmp");
        List<String> ids = new ArrayList<>();
        try(BufferedReader reader = new BufferedReader(new BufferedReader(new FileReader(id)))) {
            String userId;
            while((userId = reader.readLine()) != null) {
                ids.add(userId);
            }
            idText.setItems(FXCollections.observableArrayList(ids));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void init(Stage thisStage) {
        this.stage = thisStage;
    }

    private void warn(String s, String t) {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("WarningPane.fxml"));
        try {
            Parent parent = loader.load();
            WarningPane wp = (WarningPane)loader.getController();
            wp.setMessage(s);
            Stage w = new Stage(StageStyle.UTILITY);
            w.setTitle(t);
            w.setScene(new Scene(parent, 350,220));
            w.show();
            container.getChildren().remove(1);
            container.getChildren().get(0).setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void setLoginButtonAction() {
        container.getChildren().get(0).setVisible(false);
        container.getChildren().add(new WaitBox("登录中......"));
        if(idText.getValue().equals("") || idText.getValue().contains(" ")) {
            warn("用户名不能为空或含空格", "警告");
        } else if (passwordText.getText().equals("")) {
            warn("密码不能为空", "警告");
        } else {
            send_login login = new send_login("localhost", idText.getValue(), passwordText.getText());
            Thread t = new Thread(login);
            login.messageProperty().addListener(((observableValue, s1, t1) -> {
                switch (t1) {
                    case "timeout": {
                        warn("网络异常", "警告");
                        break;
                    }
                    case "nameOrPasswordWrong": {
                        warn("用户名或密码错误", "警告");
                        break;
                    }
                    case "wrong": {
                        warn("出现异常", "警告");
                        break;
                    }
                    case "success": {
                        userMessage = login.getUserMessage();

                        send_query_word_stock query = new send_query_word_stock("localhost");
                        Thread th = new Thread(query);
                        query.messageProperty().addListener(((observableValue1, s, t11) -> {
                            switch (t11) {
                                case "timeout": {
                                    warn("网络异常", "警告");
                                    break;
                                }
                                case "wrong": {
                                    warn("出现异常", "警告");
                                    break;
                                }
                                case "success": {
                                    wordStockMessage = query.getWordStockMessage();
                                    stage.close();
                                    onSuccess.setValue("success");
                                }
                            }
                        }));
                        th.start();
                    }
                }
            }));
            t.start();
        }
    }

    @FXML
    private void setSignupButtonAction() {
        container.getChildren().get(0).setVisible(false);
        container.getChildren().add(new WaitBox("注册中......"));
        if(idText.getValue().equals("") || idText.getValue().contains(" ")) {
            warn("用户名为空或含空格!", "警告");
        } else if (passwordText.getText().equals("")) {
            warn("密码为空", "警告");
        } else {
            send_register register = new send_register("localhost", idText.getValue(), passwordText.getText());
            Thread t = new Thread(register);
            register.messageProperty().addListener(((observableValue, s, t1) -> {
                switch (t1) {
                    case "timeout": {
                        warn("网络异常", "警告");
                        break;
                    }
                    case "nameWrong": {
                        warn("用户名已存在", "警告");
                        break;
                    }
                    case "wrong": {
                        warn("出现异常", "警告");
                        break;
                    }
                    case "success": {
                        warn("注册成功", "成功");
                        try (FileWriter writer = new FileWriter(new File("/src/IBBB/temp/userName.tmp"), true)){
                            writer.write(idText.getValue() + "\n");
                            writer.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }));
            t.start();
        }
    }
}
